package com.sky.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class DishServiceImpl implements DishService {


    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 删除菜品  和 对应的口味数据
     * @param dishDTO
     * @return
     */
    @Override
    public void saveWithFlavor(DishDTO dishDTO) {
        // 1.插入菜品信息  菜品表 (插入单条数据)
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        log.info("插入新菜品：{}",dish);
        if(ObjectUtil.isNotNull(dish)){
            // (插入单条数据)
            int i=dishMapper.save(dish);
            if(i!=0){
                log.info("插入菜品成功！成功插入条数：{}",i);
            }
        }
        // 插入菜品数据后，开启 useGeneratedKeys=true  ,通过keyProperty 获取自动生成的主键id
        Long id = dish.getId();


        // 2.获取菜品口味并且插入  菜品口味表  (批量插入数据)
        List<DishFlavor> dishFlavorList= dishDTO.getFlavors();
        if(ObjectUtil.isNotNull(dishFlavorList)&&dishFlavorList.size()>0){
            dishFlavorList.forEach(df->df.setDishId(id));// 设置口味列表对应的 菜品id
            //  (批量插入数据)
            int d=dishFlavorMapper.saveList(dishFlavorList);
            if(d!=0){
                log.info("插入口味数据成功！成功插入条数：{}",d);
            }
        }
    }

    /**
     * 分页菜品 查询参数： name , categoryId  status
     * @param dishPageQueryDTO
     * @return  PageResult
     */
    @Override
    public PageResult selectDishByNameAndCategoryIdAndStatus(DishPageQueryDTO dishPageQueryDTO) {
        // 1.创建PageHelper分页拦截对象 ,设置分页查询
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        // 创建查询对象
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishPageQueryDTO,dish);

        if(ObjectUtil.isNull(dish)){
            throw  new RuntimeException("未知错误！");
        }
        // 2.根据参数进行查询
        List<DishVO> dishList=dishMapper.selectDishByNameAndCategoryIdAndStatus(dish);
        // 3.构使用 PageInfo 来获取分页信息
        PageInfo<DishVO> pageInfo = new PageInfo<>(dishList);
        List<DishVO> dishVOList = pageInfo.getList();
        long total = pageInfo.getTotal();
        // 3.返回分页数据
        PageResult pageResult = new PageResult();
        pageResult.setTotal(total);
        pageResult.setRecords(dishVOList);
        return pageResult;
    }



    /**
     * 删除菜品  和 对应的口味数据
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public void delWithFlavor(List<Long> ids) {
        //1.判断菜品有无起售，起售禁止删除
        List<Dish> dishes = dishMapper.selectListByIds(ids);
        dishes.forEach(dish -> {
            if(dish.getStatus().equals(StatusConstant.ENABLE)){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });
        // 2.判断当前菜品是否能够删除，  有无绑定套餐
        List<Setmeal> setmealList = setmealDishMapper.selectListByDishId(ids);
        if (setmealList!=null&&setmealList.size()>0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        // 4.删除菜品  以及关联的 口味表信息
        ids.forEach(id->{
            dishMapper.delById(id);
            // 删除关联的口味表数据
            dishFlavorMapper.delByDishId(id);
        });
        // 直接批量删除
        dishMapper.delBatch(ids);
        dishFlavorMapper.delBatch(ids);
    }

    /**
     * 查询菜品 根据id
     * @param id
     * @return
     */
    @Override
    public DishVO selectOneById(Long id) {
        // 1.根据id查询菜品数据
        Dish dish = dishMapper.getById(id);
        // 2.根据菜品id查询 口味列表
        Long dishId = dish.getId();
        List<DishFlavor> flavorList=dishFlavorMapper.getByDishId(dishId);
        // 3.创建 DishVO
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        // 设置口味列表
        dishVO.setFlavors(flavorList);
        return dishVO;
    }
    /**
     * 更新菜品
     *
     * @param
     * @param dishDTO
     * @return
     */
    @Override
    @Transactional
    public void updateDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        // 1.更新菜品数据
        dishMapper.updateDish(dish);
        // 2.更新相关联的口味数据  -- 删除  再新的插入
        Long id = dishDTO.getId();
        List<DishFlavor> flavorList = dishDTO.getFlavors();
        // 删除
        dishFlavorMapper.delByDishId(id);
        // 插入
        if(flavorList!=null && flavorList.size()>0){
            flavorList.forEach(dishFlavor -> dishFlavor.setDishId(id)); // 批量设置，口味列表的dish_id 对应 菜品id
            dishFlavorMapper.inserts(flavorList); // 批量插入 菜品数据
        }
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }


    /**
     * 修改菜品 售卖状态
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    public void changeStatusById(Long id, Integer status) {
        // 1.创建修改的菜品对象信息
        Dish dish = new Dish();
        dish.setStatus(status);
        dish.setId(id);
        dishMapper.updateDish(dish);
    }


}
